import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lmmi/common/index.dart';

class TimeCapsuleState {
  final List<TimeCapsule> timeCapsules;
  final bool isLoading;
  final String? error;
  // 创建时间胶囊的状态
  final String content;
  final String? imagePath;
  final bool isCreating;
  final String? createError;
  final bool isLoadingImage;
  final bool imageUploadSuccess;

  const TimeCapsuleState({
    this.timeCapsules = const [],
    this.isLoading = false,
    this.error,
    this.content = '',
    this.imagePath,
    this.isCreating = false,
    this.createError,
    this.isLoadingImage = false,
    this.imageUploadSuccess = false,
  });

  TimeCapsuleState copyWith({
    List<TimeCapsule>? timeCapsules,
    bool? isLoading,
    String? error,
    String? content,
    String? imagePath,
    bool? isCreating,
    String? createError,
    bool? isLoadingImage = false,
    bool? imageUploadSuccess = false,
    bool resetError = false,
    bool resetImagePath = false,
    bool resetCreateError = false,
  }) {
    return TimeCapsuleState(
      timeCapsules: timeCapsules ?? this.timeCapsules,
      isLoading: isLoading ?? this.isLoading,
      error: resetError ? error : (error ?? this.error),
      content: content ?? this.content,
      imagePath: resetImagePath ? imagePath : (imagePath ?? this.imagePath),
      isCreating: isCreating ?? this.isCreating,
      createError: resetCreateError
          ? createError
          : (createError ?? this.createError),
      isLoadingImage: isLoadingImage ?? this.isLoadingImage,
      imageUploadSuccess: imageUploadSuccess ?? this.imageUploadSuccess,
    );
  }
}

class TimeCapsuleNotifier extends StateNotifier<TimeCapsuleState> {
  TimeCapsuleNotifier() : super(const TimeCapsuleState());

  Future<void> loadTimeCapsules(String userId) async {
    state = state.copyWith(isLoading: true);
    try {
      final timeCapsules = await TimeCapsuleService.getTimeCapsulesByUserId(
        userId,
      );
      await Future.delayed(const Duration(milliseconds: 300));
      state = state.copyWith(timeCapsules: timeCapsules, isLoading: false);
    } catch (e) {
      state = state.copyWith(error: e.toString(), isLoading: false);
    }
  }

  // 创建时间胶囊
  Future<void> createTimeCapsule(TimeCapsule timeCapsule) async {
    await TimeCapsuleService.createTimeCapsule(timeCapsule);
    await loadTimeCapsules(timeCapsule.userId);
  }

  // 更新文字内容
  void updateContent(String content) {
    state = state.copyWith(content: content);
  }

  // 选择图片
  Future<void> pickImage() async {
    // 开始加载状态
    state = state.copyWith(isLoadingImage: true, imageUploadSuccess: false);

    try {
      final imagePath =
          await ImagePickerUtil.pickImageFromGalleryForTimeCapsule();
      if (imagePath != null) {
        // 模拟上传处理时间，让用户看到加载效果
        await Future.delayed(const Duration(milliseconds: 800));

        // 显示成功状态
        state = state.copyWith(
          imagePath: imagePath,
          isLoadingImage: false,
          imageUploadSuccess: true,
        );

        // 短暂显示成功状态后重置
        await Future.delayed(const Duration(milliseconds: 600));
        state = state.copyWith(imageUploadSuccess: false);
      } else {
        // 用户取消选择
        state = state.copyWith(
          isLoadingImage: false,
          imageUploadSuccess: false,
        );
      }
    } catch (e) {
      debugPrint('Failed to pick image: $e');
      state = state.copyWith(isLoadingImage: false, imageUploadSuccess: false);
    }
  }

  // 删除图片
  void removeImage() {
    state = state.copyWith(imagePath: null, resetImagePath: true);
  }

  // 创建临时时间胶囊（用于传递到邮箱输入页面）
  Future<TimeCapsule?> createTemporaryTimeCapsule(String selectedTime) async {
    state = state.copyWith(
      isCreating: true,
      createError: null,
      resetCreateError: true,
      isLoadingImage: true,
    );
    final currentUser = UserService.getCurrentUser();

    try {
      final now = DateTime.now();
      final openDate = _calculateOpenDate(now, selectedTime);

      final timeCapsule = TimeCapsule(
        id: 'tc_${now.millisecondsSinceEpoch}',
        content: state.content,
        userId: currentUser!.id,
        createDate: now.toIso8601String(),
        openDate: openDate.toIso8601String(),
        description: state.content,
        isOpen: false,
        email: '',
        backupEmail: '',
        imagePath: state.imagePath,
      );

      state = state.copyWith(isCreating: false, isLoadingImage: false);
      return timeCapsule;
    } catch (e) {
      state = state.copyWith(
        isCreating: false,
        createError: 'Failed to create time capsule: $e',
        isLoadingImage: false,
      );
      return null;
    }
  }

  // 计算开启日期
  DateTime _calculateOpenDate(DateTime createDate, String timeOption) {
    switch (timeOption) {
      case 'Random':
        // 随机30-365天
        final randomDays = (DateTime.now().millisecondsSinceEpoch % 365) + 30;
        return createDate.add(Duration(days: randomDays));
      case 'Half a Year':
        return createDate.add(Duration(days: 182));
      case 'One Year':
        return createDate.add(Duration(days: 365));
      case 'Five Years':
        return createDate.add(Duration(days: 365 * 5));
      case 'Ten Years':
        return createDate.add(Duration(days: 365 * 10));
      default:
        return createDate.add(Duration(days: 365));
    }
  }

  // 重置创建状态
  void resetCreateState() {
    state = state.copyWith(
      content: '',
      imagePath: null,
      isCreating: false,
      createError: null,
      resetImagePath: true,
      resetCreateError: true,
    );
  }

  // 清空时间胶囊列表
  void clearTimeCapsules() {
    state = state.copyWith(timeCapsules: [], isLoading: false, error: null);
  }
}

// Provider定义
final timeCapsuleProvider =
    StateNotifierProvider<TimeCapsuleNotifier, TimeCapsuleState>(
      (ref) => TimeCapsuleNotifier(),
    );
